<template>
  <div style="width: 100%">
    <span v-if="inputDisabled || props.showText" class="video-box">
      <span
        v-if="videoName"
        class="cc-video-name"
        :title="videoName"
        @click="showVideo"
      >{{videoName}}</span>
    </span>
    <span v-else-if="!inputDisabled" class="video-edit-box">
      <el-upload :class="['cc-video', {'is-disabled': inputDisabled}]" action=""
        :disabled="inputDisabled"
        :http-request = "handleUpload"
        :show-file-list="false"
        accept=".mp4"
        :before-upload="handleBeforeUpload"
      >
        <cc-icon
          v-if="loading"
          style="font-size: 25px; color: #999"
          iconId="018dcab3d3dfd6e82393"
          class="spinner"
        />
        <el-button
          v-else
          :style="props.mode === 'table' ? 'margin-left: 5px;' : ''"
          size="small"
          type="primary"
          :loading="loading"
        >上传</el-button>
      </el-upload>
      <span
        v-if="videoName"
        class="cc-video-name"
        :title="videoName"
        @click="showVideo"
      >{{videoName}}</span>
    </span>

    <el-dialog
      width="800px"
      append-to-body
      title="视频查看"
      v-model="dialogVisible"
      :close-on-click-modal="false"
      :fullscreen="dialogFullscreen"
      destroy-on-close
      draggable
      class="cc-page-comp-dialog"
    >
      <template #header>
        <div class="header" @dblclick="dialogFullscreen=!dialogFullscreen">
          <div class="title">视频查看</div>
          <div class="button">
            <cc-icon
              v-if="!dialogFullscreen"
              iconId="018dca8cad1b28075ecd"
              @click="dialogFullscreen=true"
              title="最大化"
            />
            <cc-icon
              v-if="dialogFullscreen"
              iconId="018dca8cad1b9b03c47f"
              @click="dialogFullscreen=false"
              title="缩小"
            />
          </div>
        </div>
      </template>
      <video width="100%" height="100%" controls autoplay>
        <source :src="videoUrl" type="video/mp4">
        浏览器不支持视频查看
      </video>
      <template #footer>
        <el-form>
          <el-button
            size="default"
            type="info"
            @click="dialogVisible=false"
          >关闭</el-button>
        </el-form>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, nextTick, inject } from 'vue'
import { ElMessage, useDisabled, useFormItem } from "element-plus";
import api from "@/http/api";

const emit = defineEmits(['change']);
const props = defineProps({
  prop: {
    type: String,
    default: ''
  },
  width: {
    type: Number,
    default: 100
  },
  height: {
    type: Number,
    default: 100
  },
  mode: String,
  maxSize: {
    type: Number,
    default: 100
  },
  options: Object,
  showText: Boolean
});
const formData = inject('formData');

const loading = ref(true);
const fileId = ref('');
const videoName = ref('');
const videoUrl = ref('');
const inputDisabled = useDisabled();
const formItem = useFormItem();
const dialogFullscreen = ref(false);
const dialogVisible = ref(false);

const handleUpload = (data) => {
  return new Promise((resolve, reject) => {
    api.upload({'file': data.file, type: data.file.type}).then((res) => {
      loading.value = false;
      fileId.value = res.data.id;
      videoName.value = res.data.trueName;
      videoUrl.value = import.meta.env.VITE_VIDEO_PATH + res.data.id;
      formData.value[props.prop] = res.data.id;

      nextTick(() => {
        if (formItem && formItem.formItem) {
          formItem.formItem.validate('change');
        }
      });
      resolve();
    }).catch(() => {
      loading.value = false;
      reject();
    });
  });
};

const handleBeforeUpload = (file) => {
  if (loading.value) {
    ElMessage.error("视频正在上传中，请稍候再试！");
    return false;
  }
  loading.value = true;

  let isVideo = file.type.includes("video");
  if (!isVideo) {
    loading.value = false;
    ElMessage.error("上传文件类型必须是视频!");
    return false;
  }
  let isLtMaxSize = file.size / 1024 / 1024 < props.maxSize;
  if (!isLtMaxSize) {
    loading.value = false;
    ElMessage.error("上传视频大小不能超过 " + props.maxSize + "MB!");
    return false;
  }
  return isVideo && isLtMaxSize;
};

const loadData = () => {
  if (typeof formData.value[props.prop] !== "undefined"
      && formData.value[props.prop] != null
      && formData.value[props.prop] !== '') {
    fileId.value = formData.value[props.prop];
    loading.value = true;
    api.queryFile(formData.value[props.prop]).then(res => {
      loading.value = false;
      videoName.value = res.data.trueName;
      videoUrl.value = import.meta.env.VITE_VIDEO_PATH + res.data.id;
    }).catch(() => {
      loading.value = false;
    });
  } else {
    loading.value = false;
    fileId.value = '';
    videoName.value = '';
    videoUrl.value = '';
  }
};

const showVideo = () => {
  dialogVisible.value = true;
};

watch(() => formData.value[props.prop], (newVal) => {
  if ((newVal || '') === '' || (fileId.value || '') === '' || newVal !== fileId.value) {
    fileId.value = '';
    videoName.value = '';
    videoUrl.value = '';
    emit('change');
    loadData();
  }
});

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.video-edit-box {
  display: flex;
  flex-direction: row;
  .cc-video {
    justify-content: start;
    align-items: center;
    display: flex;
    margin-right: 8px;
  }
  .cc-video :deep(.el-upload) {
    display: flex;
    text-align: center;
    cursor: pointer;
    outline: 0;
    justify-content: start;
    align-items: center;
  }
  .cc-video :deep(.el-upload span) {
    display: flex;
    justify-content: start;
    align-items: center;
  }
  .cc-video:not(.is-disabled) :deep(.el-upload) {
    cursor: pointer;
  }
  .cc-video:not(.is-disabled) :deep(.el-upload:hover) {
    border-color: #409EFF;
  }
}
.video-box {
  display: flex;
  justify-content: start;
  align-items: center;
  text-align: center;
}
.cc-video-name {
  cursor: pointer;
  flex-grow: 1;
  text-align: left;
  text-overflow: ellipsis;
  overflow: hidden;
  flex-wrap: wrap;
  white-space: nowrap;
}
</style>